package Servlet;

import DAO.CustomerDAO;
import DAO.DAOFactory;
import javabean.Customer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet ("/registration")
public class RegistrationServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取表单数据
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String customerID = req.getParameter("username");
        String customerName = req.getParameter("name");
        String password = req.getParameter("password");
        String customerPhone = req.getParameter("phone");
        //封装成javabean
        Customer customer = new Customer();
        customer.setCustomerID(customerID);
        customer.setCustomerName(customerName);
        customer.setPassword(password);
        customer.setCustomerPhone(customerPhone);
        //调用DAO层
        CustomerDAO customerDAO = (CustomerDAO) DAOFactory.getCustomerDAOInstance();
        try {
            if(customerDAO.doCreate(customer)){
                req.setAttribute("message", "true");
                req.getRequestDispatcher("Login.jsp").forward(req, resp);
            }else{
                req.setAttribute("message", "false");
                req.getRequestDispatcher("Registration.jsp").forward(req, resp);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //跳转到登录页面，并将注册成功的标志添加到请求属性中
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
